package com.ms.gateway.filter;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;

import com.system.comm.utils.FrameJsonUtil;
import com.system.comm.utils.FrameMapUtil;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class AccessFilter implements GlobalFilter, Ordered {

	private static final Logger LOGGER = LoggerFactory.getLogger(AccessFilter.class);
	private static final String TOKEN = "token";

	@Override
	public int getOrder() {
		//过滤器顺序
		return 1;
	}
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		Flux<DataBuffer> requestBody = exchange.getRequest().getBody();
		String requestBodyString = "{}";
		/*if (requestBody != null) {
			requestBodyString = requestBody.toString();
			LOGGER.info("requestBodyString: {}", requestBodyString);
		}*/
		String token = exchange.getRequest().getQueryParams().getFirst(TOKEN);
		if (token == null || token.isEmpty()) {
			LOGGER.info( "token is empty..." );
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			return exchange.getResponse().setComplete();
		}

		Map<String, Object> requestBodyMap = FrameJsonUtil.toMap(requestBodyString);
		String clientId = FrameMapUtil.getString(requestBodyMap, "clientId");
		String sign = FrameMapUtil.getString(requestBodyMap, "sign");
		String time = FrameMapUtil.getString(requestBodyMap, "time");
		/*String contentType = request.getContentType();
		if (FrameStringUtil.isNotEmpty(contentType) && contentType.contains(StringCons.MULTIPART_FORM_DATA)) {
			// 获取到multipart/form-data类型的参数
			HttpServletRequestWrapper httpServletRequestWrapper = (HttpServletRequestWrapper) request;
			clientId = httpServletRequestWrapper.getRequest().getParameter("clientId");
			sign = httpServletRequestWrapper.getRequest().getParameter("sign");
			time = httpServletRequestWrapper.getRequest().getParameter("time");
		}*/

		String uri = exchange.getRequest().getURI().toString();

		/*if(FrameStringUtil.isEmpty(clientId)) {
			//处理requestBody传参的情况
			Map<String, Object> requestMap = FrameHttpRequestUtil.getReqBodyParams(request);
			clientId = FrameMapUtil.getString(requestMap, "clientId");
			sign = FrameMapUtil.getString(requestMap, "sign");
			time = FrameMapUtil.getString(requestMap, "time");
		}*/

		LOGGER.info("{ clientId:" + clientId + ", time:" + time + ", sign:" + sign + " } 请求地址: " + uri);
		/*AuthClient client = AuthUtil.get(clientId);
		if(client == null) {
			LOGGER.error("非法请求(abnormal signature): { clientId:" + clientId + ", time:" + time + ", sign:" + sign + " } 请求地址: " + uri);
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			return exchange.getResponse().setComplete();
		}*/
		/*//处理是否超额访问
		if(client.getReqMaxSecond() != null && client.getReqMaxSecond().longValue() > 0) {
			RateLimiter rateLimiter = new RateLimiter(clientId);
			if(!rateLimiter.acquireSecond(client.getReqMaxSecond().longValue())) {
				LOGGER.error("超过每秒钟最大请求数: " + client.getReqMaxSecond() + "次");
				ResponseFrame frame = new ResponseFrame();
				frame.setCode(ResponseCode.REQ_MAX_SECOND.getCode());
				frame.setMessage(ResponseCode.REQ_MAX_SECOND.getMessage() + ": " + client.getReqMaxSecond() + "次");
				ctx.getResponse().setContentType("text/html;charset=UTF-8");
				ctx.setSendZuulResponse(false);
				ctx.setResponseStatusCode(401);
				String responseResult = FrameJsonUtil.toString(frame);
				ctx.setResponseBody(responseResult);
				BizLogUtil.saveLogZuulFilter(request, responseResult);
				return null;
			}
		}
		if(client.getReqMaxHour() != null && client.getReqMaxHour().longValue() > 0) {
			RateLimiter rateLimiter = new RateLimiter(clientId);
			if(!rateLimiter.acquireHour(client.getReqMaxHour().longValue())) {
				LOGGER.error("超过每小时最大请求数: " + client.getReqMaxHour() + "次");
				ResponseFrame frame = new ResponseFrame();
				frame.setCode(ResponseCode.REQ_MAX_HOUR.getCode());
				frame.setMessage(ResponseCode.REQ_MAX_HOUR.getMessage() + ": " + client.getReqMaxHour() + "次");
				ctx.getResponse().setContentType("text/html;charset=UTF-8");
				ctx.setSendZuulResponse(false);
				ctx.setResponseStatusCode(401);
				String responseResult = FrameJsonUtil.toString(frame);
				ctx.setResponseBody(responseResult);
				BizLogUtil.saveLogZuulFilter(request, responseResult);
				return null;
			}
		}
		if(!AuthUtil.authVerify(clientId, time, sign)) {
			LOGGER.error("非法请求(abnormal signature): { clientId:" + clientId + ", time:" + time + ", sign:" + sign + " } 请求地址: " + request.getRequestURI());
			ResponseFrame frame = new ResponseFrame();
			frame.setCode(ResponseCode.ABNORMAL_SIGNATURE.getCode());
			frame.setMessage(ResponseCode.ABNORMAL_SIGNATURE.getMessage());
			ctx.getResponse().setContentType("text/html;charset=UTF-8");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			String responseResult = FrameJsonUtil.toString(frame);
			ctx.setResponseBody(responseResult);
			BizLogUtil.saveLogZuulFilter(request, responseResult);
			return null;
		}
		//判断请求地址是否通过
		if(!AuthUtil.authVerifyReqUrl(clientId, request.getRequestURI())) {
			LOGGER.error("地址: " + request.getRequestURI() + " 没有权限, clientId[" + clientId + "]");
			ResponseFrame frame = new ResponseFrame();
			frame.setCode(ResponseCode.ABNORMAL_SIGNATURE.getCode());
			frame.setMessage(ResponseCode.ABNORMAL_SIGNATURE.getMessage());
			ctx.getResponse().setContentType("text/html;charset=UTF-8");
			ctx.setSendZuulResponse(false);
			ctx.setResponseStatusCode(401);
			String responseResult = FrameJsonUtil.toString(frame);
			ctx.setResponseBody(responseResult);
			BizLogUtil.saveLogZuulFilter(request, responseResult);
			return null;
		}*/

		return chain.filter(exchange);
	}
}